﻿<template>
  <div class="container">
    <!-- 统计卡片区域 -->
    <a-row :gutter="16">
      <a-col :span="6" v-for="(card, index) in statisticsCards" :key="index">
        <div class="data-card">
          <div class="card-content">
            <div class="card-title">{{ card.title }}</div>
            <div class="card-value" :style="{ color: card.color }">{{ card.value }}</div>
            <div class="card-desc">{{ card.desc }}</div>
          </div>
          <div class="card-icon" :style="{ backgroundColor: `${card.color}1a`, color: card.color }">
            <component :is="card.icon" :style="{ fontSize: '28px' }" />
          </div>
        </div>
      </a-col>
    </a-row>

    <!-- 出库申请流程 -->
    <a-card class="general-card">
      <template #title>出库流程状态</template>
      <template #extra>
        <a-button type="primary" @click="openCreateModal">
          <template #icon><icon-plus /></template>
          新建出库单
        </a-button>
      </template>
      <a-steps :current="1" style="margin: 20px 0">
        <a-step title="创建出库单" description="录入客户需求货物" />
        <a-step title="拣货操作" description="选择库位并拣货" />
        <a-step title="发货操作" description="核对后确认发货" />
        <a-step title="完成出库" description="扣减库存完成出库" />
      </a-steps>
      
      <a-divider />
      
      <a-row :gutter="[16, 16]">
        <a-col :span="12">
          <a-statistic 
            title="本月新增出库申请" 
            :value="outboundStore.outboundStatistics?.totalOrders || 0" 
            style="margin-bottom: 12px"
          >
            <template #suffix>
              <span style="font-size: 14px; color: #52c41a; margin-left: 8px;">
                <icon-arrow-rise style="vertical-align: middle;" /> 
                {{ outboundStore.outboundStatistics?.orderGrowthRate || 0 }}%
              </span>
            </template>
          </a-statistic>
          <div ref="trendChartRef" style="height: 200px;"></div>
        </a-col>
        <a-col :span="12">
          <a-statistic 
            title="申请平均处理时间" 
            :value="outboundStore.outboundStatistics?.avgProcessHours || 0" 
            style="margin-bottom: 12px"
          >
            <template #suffix>
              <span>小时</span>
              <span :style="{ fontSize: '14px', color: outboundStore.outboundStatistics?.timeRateDirection === 'up' ? '#f5222d' : '#52c41a', marginLeft: '8px' }">
                <component :is="outboundStore.outboundStatistics?.timeRateDirection === 'up' ? IconArrowRise : IconArrowFall" style="vertical-align: middle;" /> 
                {{ Math.abs(outboundStore.outboundStatistics?.timeChangeRate || 0) }}%
              </span>
            </template>
          </a-statistic>
          <div ref="statusChartRef" style="height: 200px;"></div>
        </a-col>
      </a-row>
    </a-card>

    <!-- 出库申请列表 -->
    <a-card class="general-card">
      <template #title>出库单列表</template>
      <template #extra>
        <a-space>
          <a-select
            v-model="searchForm.status"
            placeholder="状态筛选"
            style="width: 150px"
            allow-clear
          >
            <a-option value="">全部状态</a-option>
            <a-option :value="0">已取消</a-option>
            <a-option :value="1">待拣货</a-option>
            <a-option :value="2">待发货</a-option>
            <a-option :value="3">已完成</a-option>
          </a-select>
          <a-range-picker
            v-model="searchForm.dateRange"
            style="width: 240px"
            allow-clear
          />
          <a-input-search
            v-model="searchForm.keyword"
            placeholder="搜索单号/客户"
            style="width: 200px"
            allow-clear
            @search="handleSearch"
          />
          <a-button @click="handleReset">
            <template #icon><icon-refresh /></template>
            刷新
          </a-button>
        </a-space>
      </template>
      <a-table
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :bordered="false"
        row-key="id"
        stripe
        @page-change="handlePageChange"
      >
        <template #columns>
          <a-table-column title="出库单号" data-index="code" :width="180" />
          <a-table-column title="客户名称" data-index="customerName" :width="160" />
          <a-table-column title="联系人" data-index="customerContact" :width="110" />
          <a-table-column title="仓库" data-index="warehouseName" :width="100" />
          <a-table-column title="货物数量" data-index="totalQuantity" :width="110" :sortable="{ sortDirections: ['ascend', 'descend'] }" />
          <a-table-column title="总金额" :width="110">
            <template #cell="{ record }">
              ¥{{ record.totalAmount?.toFixed(2) || '0.00' }}
            </template>
          </a-table-column>
          <a-table-column title="创建时间" data-index="createTime" :width="180" :sortable="{ sortDirections: ['ascend', 'descend'] }">
            <template #cell="{ record }">
              {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </a-table-column>
          <a-table-column title="状态" data-index="status" :width="100">
            <template #cell="{ record }">
              <a-tag :color="getStatusColor(record.status)">{{ record.statusText || getStatusText(record.status) }}</a-tag>
            </template>
          </a-table-column>
          <a-table-column title="操作" fixed="right" :width="200">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="viewDetail(record.id)">
                  <template #icon><icon-eye /></template>
                  查看
                </a-button>
                <a-button type="text" status="warning" size="small" v-if="record.status === 1" @click="startPicking(record.id)">
                  <template #icon><icon-tag /></template>
                  去拣货
                </a-button>
                <a-button type="text" status="success" size="small" v-if="record.status === 2" @click="startShipping(record.id)">
                  <template #icon><icon-send /></template>
                  去发货
                </a-button>
                <a-popconfirm
                  content="确定取消该出库单吗？"
                  position="br"
                  @ok="confirmCancel(record.id)"
                  v-if="[1, 2].includes(record.status)"
                >
                  <a-button type="text" status="danger" size="small">
                    <template #icon><icon-close-circle /></template>
                    取消
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 出库单详情模态框 -->
    <a-modal
      v-model:visible="detailVisible"
      title="出库单详情"
      :width="1100"
      :footer="false"
      :unmount-on-close="true"
    >
      <a-spin :loading="detailLoading">
        <!-- Basic Info -->
        <a-descriptions title="基本信息" :data="detailInfo" :column="3" bordered size="small" :label-style="{ width: '110px' }" />
        
        <!-- Cargo Info Table -->
        <div style="margin-top: 16px;">
          <a-typography-title :heading="6">货物信息</a-typography-title>
          <a-table 
            :data="detailItems" 
            :pagination="false" 
            :bordered="{cell:true}"
            :scroll="{ y: '240px' }" 
            row-key="id"
            stripe
            size="small"
          >
            <template #columns>
              <a-table-column title="序号" :width="50" align="center">
                 <template #cell="{ rowIndex }">{{ rowIndex + 1 }}</template>
              </a-table-column>
              <a-table-column title="货物编码" data-index="cargo.code" :width="125" align="center" ellipsis tooltip>
                <template #cell="{ record }">{{ record.cargo?.code || '-' }}</template>
              </a-table-column>
              <a-table-column title="货物名称" data-index="cargo.name" align="center" ellipsis tooltip>
                <template #cell="{ record }">{{ record.cargo?.name || '-' }}</template>
              </a-table-column>
              <a-table-column title="规格" data-index="cargo.spec" :width="110" align="center" ellipsis tooltip>
                 <template #cell="{ record }">{{ record.cargo?.spec || '-' }}</template>
              </a-table-column>
              <a-table-column title="单位" data-index="cargo.unit" :width="55" align="center">
                 <template #cell="{ record }">{{ record.cargo?.unit || '-' }}</template>
              </a-table-column>
              <a-table-column title="请求数量" data-index="quantity" :width="85" align="center"/>
              <a-table-column title="单价(元)" data-index="unit_price" :width="95" align="center">
                <template #cell="{ record }">¥{{ Number(record.unit_price || 0).toFixed(2) }}</template>
              </a-table-column>
              <a-table-column title="总价(元)" :width="105" align="center">
                <template #cell="{ record }">¥{{ (Number(record.quantity || 0) * Number(record.unit_price || 0)).toFixed(2) }}</template>
              </a-table-column>
              <a-table-column title="拣货数量" data-index="picked_quantity" :width="85" align="center">
                 <template #cell="{ record }">{{ record.picked_quantity ?? 0 }}</template>
              </a-table-column>
              <a-table-column title="发货数量" data-index="shipped_quantity" :width="85" align="center">
                 <template #cell="{ record }">{{ record.shipped_quantity ?? 0 }}</template>
              </a-table-column>
              <a-table-column title="备注" data-index="note" align="center" ellipsis tooltip>
                 <template #cell="{ record }">{{ record.note || '-' }}</template>
              </a-table-column>
            </template>
          </a-table>
        </div>
        
        <!-- Operation Logs (Commented out for now) -->
        <!-- 
        <div style="margin-top: 20px;">
          <a-typography-title :heading="6">操作记录</a-typography-title>
          <a-timeline v-if="detailLogs && detailLogs.length > 0">
             <a-timeline-item v-for="log in detailLogs" :key="log.id" :label="dayjs(log.timestamp).format('YYYY-MM-DD HH:mm')">
               {{ log.operatorName }} {{ log.action }}: {{ log.details }}
             </a-timeline-item>
           </a-timeline>
           <a-empty v-else />
        </div>
         -->

        <div style="margin-top: 24px; display: flex; justify-content: center; gap: 16px;">
          <a-button @click="closeDetail">关闭</a-button>
          <a-button v-if="currentDetail && currentDetail.status === 1" type="primary" status="warning" @click="startPicking(currentDetail.id)">去拣货</a-button>
          <a-button v-if="currentDetail && currentDetail.status === 2" type="primary" status="success" @click="startShipping(currentDetail.id)">去发货</a-button>
          <a-button v-if="currentDetail && [1, 2].includes(currentDetail.status)" type="primary" status="danger" @click="confirmCancel(currentDetail.id)">取消出库</a-button>
        </div>
      </a-spin>
    </a-modal>

    <!-- 新建出库单模态框 -->
    <a-modal
      v-model:visible="createModalVisible"
      title="新建出库单"
      :width="1000"
      @ok="handleCreateSubmit"
      @cancel="handleCreateCancel"
      :unmount-on-close="true"
      :mask-closable="false"
      :ok-loading="createLoading"
    >
      <a-form ref="createFormRef" :model="createForm" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="customerId" label="客户" :rules="[{ required: true, message: '请选择客户'}]">
              <a-select 
                v-model="createForm.customerId" 
                placeholder="请选择客户" 
                allow-search 
                :loading="loadingCustomers"
              >
                <!-- 使用 customerStore.customerList -->
                <a-option v-for="customer in customerList" :key="customer.id" :value="customer.id">{{ customer.name }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
             <a-form-item field="warehouseId" label="仓库" :rules="[{ required: true, message: '请选择仓库'}]">
               <a-select 
                 v-model="createForm.warehouseId" 
                 placeholder="请选择仓库"
                 :loading="loadingWarehouses"
               >
                 <a-option v-for="warehouse in warehouseList" :key="warehouse.id" :value="warehouse.id">{{ warehouse.name }}</a-option>
               </a-select>
             </a-form-item>
          </a-col>
         </a-row>
         <a-row :gutter="16">  <!-- 新增一行用于放置类型选择 -->
           <a-col :span="12">
             <a-form-item field="type" label="出库类型" :rules="[{ required: true, message: '请选择出库类型'}]">
               <a-select v-model="createForm.type" placeholder="请选择出库类型">
                 <a-option :value="1">销售出库</a-option>
                 <a-option :value="2">退货出库</a-option>
                 <a-option :value="3">其他出库</a-option>
                 <!-- 根据实际需要添加更多类型 -->
               </a-select>
             </a-form-item>
           </a-col>
         </a-row>
        <a-form-item field="remark" label="备注">
            <a-textarea v-model="createForm.remark" placeholder="请输入备注信息" :auto-size="{minRows:2,maxRows:4}"/>
        </a-form-item>

        <!-- 货物信息区域 -->
        <a-divider>货物信息</a-divider>
        <a-row :gutter="16" align="end" style="margin-bottom: 16px;">
          <a-col :span="18">
            <a-form-item label="选择货物添加到列表" hide-label>
              <a-select
                v-model="selectedProductId"
                placeholder="搜索或选择货物 (先选择仓库信息)"
                allow-search
                show-extra-options
                :options="productOptions"
                :loading="loadingProducts"
                :disabled="!createForm.warehouseId"
                :filter-option="(inputValue, option) => option.label.toLowerCase().includes(inputValue.toLowerCase())"
                @change="addProduct"
              >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 货物明细表格 -->
        <a-table 
          :data="createForm.items"
          :pagination="false" 
          row-key="productId" 
          :bordered="{cell:true}"
        >
          <template #columns>
            <a-table-column title="货物名称" data-index="productName" />
            <a-table-column title="规格" data-index="specification" />
            <a-table-column title="单位" data-index="unit" />
            <a-table-column title="可用库存" data-index="availableQuantity" :width="100"/> 
            <a-table-column title="请求数量" :width="150">
              <template #cell="{ record }">
                <a-input-number 
                  v-model="record.requestedQuantity"
                  placeholder="输入数量"
                  :min="1"
                  :max="record.availableQuantity" 
                  :precision="0"
                  mode="button"
                  style="width: 120px;"
                />
              </template>
            </a-table-column>
            <a-table-column title="单价 (元)" data-index="unitPrice">
              <template #cell="{ record }">
                <span>¥{{ record.unitPrice?.toFixed(2) || '0.00' }}</span>
              </template>
            </a-table-column>
             <a-table-column title="操作" :width="80">
               <template #cell="{ record, rowIndex }">
                 <a-button type="text" status="danger" size="small" @click="removeProduct(rowIndex)">
                   <template #icon><icon-delete /></template>
                 </a-button>
               </template>
             </a-table-column>
          </template>
        </a-table>

       </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, nextTick, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { Message, Modal } from '@arco-design/web-vue'
import { 
  IconSearch, 
  IconRefresh, 
  IconDownload, 
  IconPlus, 
  IconEye, 
  IconMore, 
  IconCheck,
  IconCalendar,
  IconCheckCircle,
  IconCloseCircle,
  IconFile,
  IconStorage,
  IconClockCircle,
  IconExclamationCircle,
  IconArrowRise,
  IconArrowFall,
  IconTag,
  IconSend,
  IconDelete
} from '@arco-design/web-vue/es/icon'
import { useOutboundStore } from '@/stores/outbound'
import { useWarehouseStore } from '@/stores/warehouse'
import { useCustomerStore } from '@/stores/customer'
import { useCargoStore } from '@/stores/cargo'
import { formatOutboundAmount } from '@/utils/outbound'
import { markRaw } from 'vue'
import dayjs from 'dayjs'
import { getOutboundList, getOutboundDetail, getOutboundStatistics, updateOutboundStatus } from '@/api/outbound'
import * as echarts from 'echarts'

const router = useRouter()
const outboundStore = useOutboundStore()
const warehouseStore = useWarehouseStore()
const customerStore = useCustomerStore()
const cargoStore = useCargoStore()

// 添加统计相关变量
const statisticsLoading = ref(false);
const statisticsData = ref(null);

// 统计卡片数据 - 使用ref而非computed
const statisticsCards = ref([
  {
    title: '待拣货出库',
    value: 0, 
    desc: '等待拣货',
    icon: markRaw(IconTag),
    color: '#FF7D00'
  },
  {
    title: '待发货出库',
    value: 0,
    desc: '等待发货',
    icon: markRaw(IconSend),
    color: '#165DFF'
  },
  {
    title: '今日已发货',
    value: 0, 
    desc: '今日完成发货',
    icon: markRaw(IconClockCircle),
    color: '#00B42A'
  },
  {
    title: '已取消订单',
    value: 0,
    desc: '已取消的订单',
    icon: markRaw(IconExclamationCircle),
    color: '#F53F3F'
  }
]);

// 状态
const loading = computed(() => outboundStore.loading)
const tableData = ref([])
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});

const searchForm = ref({
  status: '',
  dateRange: [],
  keyword: ''
})

const actionModal = ref({
  visible: false,
  type: '',
  title: '',
  record: null
})
const actionForm = ref({
  approved: true,
  reason: ''
})

// 使用数字作为 key，并确保与后端一致
const OUTBOUND_STATUS_TEXT = {
  0: '已取消',      // StatusOutboundCancelled
  1: '待拣货',      // StatusOutboundWaitingPicking
  2: '待发货',      // StatusOutboundWaitingShipping
  3: '已完成'       // StatusOutboundCompleted
};

// 获取状态对应的颜色 (使用数字 key)
function getStatusColor(status) {
  // 使用出库store中的状态颜色函数
  return outboundStore.getOutboundStatusColor(status);
}

// 获取状态对应的文本 (使用数字 key)
function getStatusText(status) {
  // 使用出库store中的状态文本函数
  return outboundStore.getOutboundStatusText(status);
}

// 获取统计数据
const getStatisticsData = async () => {
  try {
    statisticsLoading.value = true;
    console.log('正在获取出库统计数据...');
    
    // 调用Store方法获取统计数据
    const stats = await outboundStore.getOutboundStatistics();
    
    if (stats) {
      statisticsData.value = stats;
      console.log('统计数据获取成功:', stats);
      
      // 更新统计卡片数据 - 直接更新ref变量
      statisticsCards.value = [
        {
          title: '待拣货出库单',
          value: stats.pendingPicking || 0,
          desc: '需要仓库人员处理',
          color: '#fa8c16',
          icon: markRaw(IconCalendar)
        },
        {
          title: '待发货出库单',
          value: stats.pendingShipping || 0,
          desc: '等待发货操作',
          color: '#2f54eb',
          icon: markRaw(IconStorage)
        },
        {
          title: '今日已发货',
          value: stats.shippedToday || 0,
          desc: '今日完成发货',
          color: '#52c41a',
          icon: markRaw(IconCheckCircle)
        },
        {
          title: '已取消出库单',
          value: stats.exceptionOrders || 0,
          desc: '已取消的订单',
          color: '#f5222d',
          icon: markRaw(IconExclamationCircle)
        }
      ];
      
      // 更新图表
      nextTick(() => {
        updateCharts();
      });
    } else {
      console.warn('获取统计数据失败: 返回空数据');
      // 使用默认值初始化卡片数据
      setDefaultStatisticsData();
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
    Message.error('获取统计数据失败，将使用默认值');
    
    // 使用默认值初始化卡片数据
    setDefaultStatisticsData();
  } finally {
    statisticsLoading.value = false;
  }
};

// 设置默认统计数据
const setDefaultStatisticsData = () => {
  statisticsData.value = {
    pendingPicking: 0,
    pendingShipping: 0,
    shippedToday: 0,
    exceptionOrders: 0
  };
  
  // 更新统计卡片为默认值
  statisticsCards.value = [
    {
      title: '待拣货出库单',
      value: 0,
      desc: '需要仓库人员处理',
      color: '#fa8c16',
      icon: markRaw(IconCalendar)
    },
    {
      title: '待发货出库单',
      value: 0,
      desc: '等待发货操作',
      color: '#2f54eb',
      icon: markRaw(IconStorage)
    },
    {
      title: '今日已发货',
      value: 0,
      desc: '今日完成发货',
      color: '#52c41a',
      icon: markRaw(IconCheckCircle)
    },
    {
      title: '已取消出库单',
      value: 0,
      desc: '已取消的订单',
      color: '#f5222d',
      icon: markRaw(IconExclamationCircle)
    }
  ];
};

// 获取列表数据
const fetchList = async () => {
  try {
    // 准备搜索参数
    const searchParams = {
      page: pagination.value.current,
      pageSize: pagination.value.pageSize,
      status: searchForm.value.status || undefined, // Handle empty string
      keyword: searchForm.value.keyword || undefined,
      startDate: searchForm.value.dateRange?.[0] ? dayjs(searchForm.value.dateRange[0]).format('YYYY-MM-DD') : undefined,
      endDate: searchForm.value.dateRange?.[1] ? dayjs(searchForm.value.dateRange[1]).format('YYYY-MM-DD') : undefined,
    };
    // 移除undefined值
    Object.keys(searchParams).forEach(key => searchParams[key] === undefined && delete searchParams[key]);

    console.log('获取出库单列表, 参数:', searchParams);
    
    // 调用store获取数据
    const responseData = await outboundStore.getOutboundList(searchParams);
    
    console.log('出库单列表API响应:', responseData);
    
    if (responseData) {
      console.log('出库单列表获取成功:', responseData);
      // 使用store中的数据更新本地状态
      tableData.value = outboundStore.outboundList; 
      
      // 同步分页状态
      pagination.value.current = outboundStore.pagination.current;
      pagination.value.pageSize = outboundStore.pagination.pageSize;
      pagination.value.total = outboundStore.pagination.total;
      
      // 如果有数据但统计卡片未显示，强制刷新统计数据
      if (tableData.value.length > 0 && 
          (!outboundStore.shippingStatistics || 
           (outboundStore.shippingStatistics.pendingPicking === 0 && 
            outboundStore.shippingStatistics.pendingShipping === 0 && 
            outboundStore.shippingStatistics.total === 0))) {
        console.log('有出库单数据但统计信息为空，重新获取统计数据');
        await getStatisticsData();
      }
    } else {
      console.warn('获取出库单列表返回空数据');
      tableData.value = [];
      pagination.value.total = 0;
    }
  } catch (error) {
    console.error('获取出库单列表失败:', error); 
    tableData.value = [];
    pagination.value.total = 0;
    Message.error('获取出库单列表失败，请稍后再试');
  }
}

// 搜索
function handleSearch() {
  pagination.value.current = 1
  fetchList()
}

// 重置
function handleReset() {
  searchForm.value = {
    status: '',
    dateRange: [],
    keyword: ''
  }
  handleSearch()
}

// 导出
async function handleExport() {
  try {
    const params = {
      ...searchForm.value,
      startDate: searchForm.value.dateRange?.[0],
      endDate: searchForm.value.dateRange?.[1]
    }
    await outboundStore.exportOutbound(params)
    Message.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
  }
}

// 打开新建模态框
function openCreateModal() {
  createForm.value = {
    customerId: null,
    warehouseId: null,
    type: null,
    remark: '',
    items: [] 
  };
  selectedProductId.value = null;
  createFormRef.value?.clearValidate();
  // 获取或确认数据已加载
  if (!customerList.value.length || !warehouseList.value.length || !productList.value.length) {
      fetchSelectData();
  }
  createModalVisible.value = true;
}

// 处理新建提交
async function handleCreateSubmit() {
  createLoading.value = true;
  try {
    const errors = await createFormRef.value?.validate();
    if (errors) {
      console.log("Form validation errors:", errors);
      return; 
    }
    
    if (!createForm.value.items || createForm.value.items.length === 0) {
        Message.error('请至少添加一个出库货物');
        return;
    }
    for (const item of createForm.value.items) {
        if (!item.requestedQuantity || item.requestedQuantity <= 0) {
            Message.error(`货物 ${item.productName} 的请求数量必须大于 0`);
            return;
        }
        if (item.requestedQuantity > item.availableQuantity) {
            Message.error(`货物 ${item.productName} 的请求数量 (${item.requestedQuantity}) 不能超过可用库存 (${item.availableQuantity})`);
            return;
        }
    }

    console.log("Validated form data:", JSON.parse(JSON.stringify(createForm.value)));
    
    // 格式化提交的数据
    const submitData = {
        customer_id: createForm.value.customerId,
        warehouse_id: createForm.value.warehouseId,
        type: createForm.value.type,
        remark: createForm.value.remark,
        items: createForm.value.items.map(item => ({
            cargo_id: item.productId,
            quantity: item.requestedQuantity,
            unit_price: item.unitPrice || 0
        }))
    };
    console.log("Data to be submitted:", submitData);

    // 调用 store action (使用 outboundStore)
    Message.info('正在提交...');
    const success = await outboundStore.createOutbound(submitData); // 使用 outboundStore 的 action
    // const success = true; 
    // await new Promise(resolve => setTimeout(resolve, 1000));

    if (success) {
      Message.success('新建出库单成功');
      createModalVisible.value = false; 
      fetchList(); // 刷新列表
    } else {
      Message.error('新建出库单失败，请检查网络或联系管理员');
    }

  } catch (error) {
      console.error("Error submitting create form:", error);
      Message.error('提交失败，请稍后重试');
  } finally {
      createLoading.value = false;
  }
}

// 处理新建取消
function handleCreateCancel() {
  createModalVisible.value = false;
}

// 查看详情
async function viewDetail(id) {
  detailVisible.value = true;
  detailLoading.value = true;
  try {
    console.log('正在获取出库单详情, ID:', id);
    const detailData = await outboundStore.getOutboundDetail(id);
    
    if (detailData) {
      currentDetail.value = detailData;
      
      // Helper for robust field display
      const displayValue = (value) => value ? value : '-';
      const displayUser = (user) => (user?.nickname || user?.username) ? (user.nickname || user.username) : '-';
      const displayTime = (time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-';

      const typeMap = { 1: '销售出库', 2: '退货出库', 3: '其他出库' };
      const baseInfo = [
        { label: '出库单号', value: displayValue(detailData.code) },
        { label: '状态', value: getStatusText(detailData.status) }, 
        { label: '出库类型', value: typeMap[detailData.type] || `未知 (${detailData.type})` },
        { label: '客户名称', value: displayValue(detailData.customer?.name) },
        { label: '客户联系人', value: displayValue(detailData.customer?.contact) },
        { label: '客户电话', value: displayValue(detailData.customer?.phone) },
        { label: '出库仓库', value: displayValue(detailData.warehouse?.name) },
        { label: '创建人', value: displayUser(detailData.user) },
        { label: '创建时间', value: displayTime(detailData.created_at) },
      ];

      // Add approval info if available
      if (detailData.approve_user || detailData.approve_time || detailData.approve_note) { // Check if any approval info exists
        baseInfo.push(
          { label: '审核人', value: displayUser(detailData.approve_user) },
          { label: '审核时间', value: displayTime(detailData.approve_time) },
          { label: '审核备注', value: displayValue(detailData.approve_note) }
        );
      }
      // Add picking info if available
      if (detailData.pick_user || detailData.pick_time) {
         baseInfo.push(
           { label: '拣货人', value: displayUser(detailData.pick_user) },
           { label: '拣货时间', value: displayTime(detailData.pick_time) },
           { label: '', value: '', span: 1} // Add placeholder for alignment if needed
         );
      }
      // Add shipping info if available
      if (detailData.ship_user || detailData.ship_time) {
        baseInfo.push(
          { label: '发货人', value: displayUser(detailData.ship_user) },
          { label: '发货时间', value: displayTime(detailData.ship_time) },
           { label: '', value: '', span: 1} // Add placeholder for alignment if needed
          // Add tracking info if available
        );
      }
      
      baseInfo.push({ label: '订单备注', value: displayValue(detailData.note), span: 3 }); // Use helper

      detailInfo.value = baseInfo;
      
      // 确保items数据存在
      if (detailData.items && Array.isArray(detailData.items)) {
        console.log('出库单详情货物数据:', detailData.items);
        detailItems.value = detailData.items;
      } else {
        console.warn('出库单详情货物数据为空');
        detailItems.value = [];
      }
      // detailLogs.value = detailData.logs || []; // Keep logs commented out

    } else {
      console.error('获取出库单详情失败: 未返回数据');
      Message.error('获取出库单详情失败: 无数据');
      closeDetail();
    }
  } catch (error) {
    console.error('获取出库单详情出错:', error);
    Message.error('获取出库单详情时发生错误');
    closeDetail();
  } finally {
    detailLoading.value = false;
  }
}

// 开始拣货
function startPicking(id) {
  router.push({ name: 'PickingOperation', params: { id } });
}

// 开始发货
function startShipping(id) {
  router.push({ name: 'ShippingOperation', params: { id } });
}

// 取消出库
async function cancelOutbound(id) {
  try {
    // Assuming store handles API call and messaging
    const success = await outboundStore.updateOutboundStatus(id, 0); // 使用正确的状态码0表示取消
    if (success) {
      fetchList(); // Refresh list on success
    }
  } catch (error) {
    console.error('取消出库申请时出错:', error);
    // Store should show error message
  }
}

// 确认取消
function confirmCancel(id) {
    Modal.confirm({
        title: '确认取消',
        content: '确定要取消该出库单吗？此操作可能无法撤销。',
        okText: '确定取消',
        cancelText: '关闭',
        onOk: () => cancelOutbound(id),
    });
}

// 关闭详情
function closeDetail() {
  detailVisible.value = false;
  currentDetail.value = null;
  detailInfo.value = [];
  detailItems.value = [];
  // detailLogs.value = [];
}

// 分页变化
function handlePageChange(page) {
  pagination.value.current = page;
  fetchList();
}

// 初始化
onMounted(async () => {
  try {
    console.log('出库单列表组件初始化...');
    
    // 先获取统计数据
    await getStatisticsData();
    
    // 初始化图表
    initCharts();
    
    // 然后获取列表数据
    await fetchList();
    
    // 最后加载选择框数据
    await fetchSelectData();
    
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);
    
    console.log('出库单页面初始化完成');
  } catch (error) {
    console.error('初始化出错:', error);
    Message.error('页面初始化失败，请刷新重试');
  }
});

// --- 模态框状态 (保持不变) ---
const detailVisible = ref(false);
const detailLoading = ref(false);
const currentDetail = ref(null);
const detailInfo = ref([]);
const detailItems = ref([]);
// const detailLogs = ref([]);

// --- 新建模态框状态和表单 --- 
const createModalVisible = ref(false);
const createFormRef = ref(null);
const createForm = ref({
    customerId: null,
    warehouseId: null,
    type: null,
    remark: '',
    items: [] 
});
const createLoading = ref(false); // 控制提交按钮 loading

// --- 用于下拉选择的数据 --- 
const customerList = computed(() => customerStore.customerDropdownList || []);
const loadingCustomers = computed(() => customerStore.dropdownLoading);

// 从 warehouseStore 获取仓库列表
const warehouseList = computed(() => warehouseStore.warehouseList || []);
const loadingWarehouses = computed(() => warehouseStore.warehouseLoading);

// --- 货物选择相关 --- 
const selectedProductId = ref(null); 
// 从 cargoStore 获取货物列表
const productList = computed(() => cargoStore.cargoList || []);
const loadingProducts = computed(() => cargoStore.loading);
// 将货物列表转换为 Select 组件的 options 格式 (显示可用库存)
const productOptions = computed(() => 
  productList.value
    .filter(p => (p.stock_quantity || 0) > 0) // 只显示有库存的货物
    .map(p => ({ 
        value: p.id, 
        label: `${p.name} ${p.spec ? `(${p.spec})` : (p.specification ? `(${p.specification})` : '')} - 库存: ${p.stock_quantity || 0}`,
        disabled: (p.stock_quantity || 0) <= 0 // 禁用无库存货物
    }))
);

// 获取下拉列表数据
async function fetchSelectData() {
    try {
        // 并行获取客户、仓库数据
        await Promise.all([
            customerStore.fetchCustomerDropdownList(),
            warehouseStore.fetchWarehouses(), 
        ]);
        
        // 确保仓库已选择，再获取可用货物
        if (createForm.value.warehouseId) {
            // 获取有库存的货物列表
            await cargoStore.getInventoryProductList(createForm.value.warehouseId);
        }
    } catch (error) {
        console.error("Error fetching select data:", error);
        Message.error("获取基础数据失败，请稍后重试");
    } finally {
        // Loading states handled by computed properties
    }
}

// 监听仓库选择变化，自动获取该仓库的可用货物
watch(() => createForm.value.warehouseId, async (newWarehouseId) => {
    if (newWarehouseId) {
        // 清空已选货物列表
        createForm.value.items = [];
        // 获取该仓库的可用货物
        await cargoStore.getInventoryProductList(newWarehouseId);
    }
});

// 添加货物到列表
function addProduct() {
  if (!selectedProductId.value) return;

  const existingItem = createForm.value.items.find(item => item.productId === selectedProductId.value);
  if (existingItem) {
    Message.warning('该货物已在列表中');
    setTimeout(() => selectedProductId.value = null, 0); 
    return;
  }
  
  // 从 cargoStore 的 productList (cargoList) 中查找货物信息
  const product = productList.value.find(p => p.id === selectedProductId.value);
  if (product) {
    if ((product.stock_quantity || 0) <= 0) {
        Message.error(`货物 ${product.name} 库存不足，无法添加`);
        setTimeout(() => selectedProductId.value = null, 0); 
        return;
    }
    
    // 获取规格，优先使用 spec，如果不存在则使用 specification
    const specification = product.spec || product.specification || '';
    
    // << 新增日志：打印选中的货物信息 >>
    console.log('Selected Product for Outbound:', JSON.parse(JSON.stringify(product)));
    
    createForm.value.items.push({
      productId: product.id,
      productName: product.name,
      specification: specification, // 使用正确获取的规格
      unit: product.unit || '',
      availableQuantity: product.stock_quantity || 0, // 保存可用库存用于验证
      requestedQuantity: 1, // 默认请求数量为 1
      unitPrice: product.price || 0 // 新增：使用从货物信息获取的价格初始化，如果不存在则为 0
    });
  } else {
      Message.error('未找到所选货物信息');
  }
  setTimeout(() => selectedProductId.value = null, 0); 
}

// 从列表移除货物
function removeProduct(index) {
  createForm.value.items.splice(index, 1);
}

// 图表相关
const trendChartRef = ref(null);
const statusChartRef = ref(null);
let trendChart = null;
let statusChart = null;

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    if (trendChartRef.value && !trendChart) {
      trendChart = echarts.init(trendChartRef.value);
    }
    if (statusChartRef.value && !statusChart) {
      statusChart = echarts.init(statusChartRef.value);
    }
    updateCharts();
  });
};

// 更新图表数据
const updateCharts = () => {
  if (trendChart) {
    // 模拟月度趋势数据
    const months = ['1月', '2月', '3月', '4月', '5月', '6月'];
    const counts = [10, 15, 8, 12, 20, 16];
    
    trendChart.setOption({
      title: {
        text: '出库单月度趋势',
        left: 'center',
        top: 0,
        textStyle: {
          fontSize: 14
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '25%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: months,
        axisLabel: {
          fontSize: 10
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          fontSize: 10
        }
      },
      series: [
        {
          name: '出库单数',
          type: 'bar',
          barWidth: '60%',
          data: counts,
          itemStyle: {
            color: '#FF7D00'
          }
        }
      ]
    });
  }
  
  if (statusChart) {
    // 根据实际统计数据创建状态分布图
    const pending = statisticsData.value?.pendingPicking || 0;
    const shipping = statisticsData.value?.pendingShipping || 0;
    const completed = statisticsData.value?.completed || 0;
    const cancelled = statisticsData.value?.cancelled || 0;
    
    const statusData = [
      { name: '待拣货', value: pending, itemStyle: { color: '#FF7D00' } },
      { name: '待发货', value: shipping, itemStyle: { color: '#165DFF' } },
      { name: '已完成', value: completed, itemStyle: { color: '#00B42A' } },
      { name: '已取消', value: cancelled, itemStyle: { color: '#F53F3F' } }
    ];
    
    statusChart.setOption({
      title: {
        text: '出库单状态分布',
        left: 'center',
        top: 0,
        textStyle: {
          fontSize: 14
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        top: 30,
        itemWidth: 10,
        itemHeight: 10,
        textStyle: {
          fontSize: 10
        },
        data: statusData.map(item => item.name)
      },
      series: [
        {
          name: '订单状态',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['60%', '55%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 5,
            borderColor: '#fff',
            borderWidth: 1
          },
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 12,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: statusData
        }
      ]
    });
  }
};

// 处理窗口大小变化，重新调整图表大小
const handleResize = () => {
  if (trendChart) {
    trendChart.resize();
  }
  if (statusChart) {
    statusChart.resize();
  }
};

// 在组件卸载时移除事件监听和销毁图表实例
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (trendChart) {
    trendChart.dispose();
    trendChart = null;
  }
  if (statusChart) {
    statusChart.dispose();
    statusChart = null;
  }
});

// 监听统计数据变化，更新图表
watch(
  () => statisticsData.value,
  (newVal) => {
    if (newVal) {
      nextTick(() => {
        updateCharts();
      });
    }
  },
  { deep: true }
);

// 监听出库单列表变化，刷新图表
watch(
  () => outboundList.value,
  () => {
    nextTick(() => {
      updateCharts();
    });
  },
  { deep: true }
);
</script>

<style lang="less" scoped>
.container {
  padding: 20px;
}

.data-card {
  height: 120px;
  padding: 20px;
  display: flex;
  background-color: var(--color-bg-2);
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  margin-bottom: 16px;

  &:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  .card-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .card-title {
    font-size: 14px;
    color: var(--color-text-2);
    margin-bottom: 8px;
  }

  .card-value {
    font-size: 28px;
    font-weight: 600;
    margin-bottom: 8px;
  }

  .card-desc {
    font-size: 12px;
    color: var(--color-text-3);
  }

  .card-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 36px;
    opacity: 0.8;
    width: 60px;
    height: 60px;
    border-radius: 50%;
    margin-left: 12px;
  }
}

.general-card {
  margin-bottom: 16px;
  
  :deep(.arco-card-header) {
    height: 52px;
    padding: 16px 20px;
    border-bottom: 1px solid var(--color-border);
  }
}
</style>

<script>
export default {
  name: 'OutboundList'
}
</script> 